import React, {Component, PropTypes} from 'react'
import ReactDOM from "react-dom"
import AJAX from "../../lib/ajax";
import Tools from "../../lib/tools"
import InfiniteScroll from 'react-infinite-scroller'; // 无限加载
import Toast from '../MyPackage/components/Toast'
require('../../lib/rem');
require('../../styles/lux.less');
require('../../styles/common.less');
require('../../styles/resetWeui.less');
require('./SuggestionDetail.less');
import { addErrorListener } from "../../lib/handleError"
import weixinShare from '../../lib/weixinShare';

//定义id
const feedback_id = Tools.getParams().feedback_id;

class SuggestionDetail extends Component {
    constructor(props) {
        super(props);
        this.state = {
            feedback: [],//反馈列表
            can_load_time: 1,//能够加载次数
            isLoadMore: true,//是否可以加载更多
            load_time: 0,//已经加载次数
            page: 1,
            psize: 10,
            addContent: '',//添加的内容

        };
        this.createDom = this.createDom.bind(this);
        this.loadMore = this.loadMore.bind(this);
        this.sendSuggestion = this.sendSuggestion.bind(this);
        this.handleChangeContent = this.handleChangeContent.bind(this);
        this.inputFocus = this.inputFocus.bind(this);
    }

    componentWillMount() {
        addErrorListener()()
        weixinShare.hideAll()
    }

    componentDidMount() {
        AJAX.appendBaiduAnalysis()
        
        const _this = this;
        AJAX.request("feedback_detail", {page: 1, psize: this.state.psize, feedback_id: feedback_id}, (data) => {

            if (data.code == 0) {
                let feedServer_list = data.body.list || [];
                let count = data.body.count || 0;
                this.setState({
                    feedback: feedServer_list.reverse().concat(this.state.feedback),
                    can_load_time: parseInt((count - 1) / this.state.psize + 1),
                    load_time: this.state.load_time + 1,
                    page: this.state.page + 1
                });
                setTimeout(function () {
                    //_this.refs['scrollIntoView'].scrollIntoView({block: 'end', behavior: 'smooth'});
                    _this.refs['tab_panel'].scrollTop = _this.refs['tab_panel'].scrollHeight
                }, 0)
            }

        })
    }

    loadMore() {
        if (this.state.load_time >= this.state.can_load_time) {
            this.setState({
                isLoadMore: false
            });
            return
        }
        const feedback_id = Tools.getParams().feedback_id;

        //记录当前滚动的位置
        let _this_scrollHeight = this.refs['tab_panel'].scrollHeight;
        AJAX.request("feedback_detail", {
            page: this.state.page,
            psize: this.state.psize,
            feedback_id: feedback_id
        }, (data) => {
            if (data.code == 0) {
                let feedServer_list = data.body.list || [];
                let count = data.body.count || 0;
                this.setState({
                    feedback: feedServer_list.reverse().concat(this.state.feedback),
                    can_load_time: parseInt((count - 1) / this.state.psize + 1),
                    load_time: this.state.load_time + 1,
                    page: this.state.page + 1
                });

                //记录当前内容高度
                let _that_scrollHeight = this.refs['tab_panel'].scrollHeight;
                //若果还有下一页,滚动条位置拉伸到当前滚动位置
                if (parseInt((count - 1) / this.state.psize + 1) == this.state.load_time) {
                    this.refs['tab_panel'].scrollTop = _that_scrollHeight - _this_scrollHeight
                } else if (parseInt((count - 1) / this.state.psize + 1) > (this.state.load_time)) {
                    this.refs['tab_panel'].scrollTop = _this_scrollHeight
                }
            }

        })

    }

    //添加新留言
    handleChangeContent(e) {
        this.setState({
            addContent: e.target.value.replace(/\ud83d[\udc00-\ude4f\ude80-\udfff]/g, '')
        })
    }

    //留言框获取焦点
    inputFocus() {
        this.refs['tab_panel'].scrollTop = this.refs['tab_panel'].scrollHeight
    }

    //发送消息
    sendSuggestion() {
        if (this.state.addContent.length == 0) {
            Toast.warn({
                content: '内容不能为空'
            });
            return
        }
        if (this.state.addContent.length > 100) {
            Toast.warn({
                content: '内容过长，请输入100字以内'
            });
            return
        }

        AJAX.request("feedback_add", {content: this.state.addContent, feedback_id: feedback_id}, (data) => {
            if (data.code == 0) {
                this.setState({
                    addContent: ''
                });
                AJAX.request("feedback_detail", {
                    page: 1,
                    psize: this.state.psize,
                    feedback_id: feedback_id
                }, (data) => {
                    if (data.code == 0) {
                        let feedServer_list = data.body.list || [];
                        let count = data.body.count || 0;
                        this.setState({
                            feedback: feedServer_list.reverse(),
                            can_load_time: parseInt((count - 1) / this.state.psize + 1),
                            load_time: this.state.load_time + 1,
                            page: this.state.page + 1
                        })

                    }

                })
            }

        });
        //添加请求
        //第一页详情请求
        this.refs['tab_panel'].scrollTop = this.refs['tab_panel'].scrollHeight
    }


    createDom() {

        const serverDate = this.state.feedback.map(item=>
            <div className={item.is_inner == 0 ? 'role_1' : 'role_2'}>
                <p className="time"><span>{item.create_time}</span></p>
                <div>
                    <div className="user_img">
                        <img src={item.headimgurl} alt=""/>
                    </div>
                    <div className="user_say">
                        <p>{item.content}</p>
                        {
                            item.img_url &&
                            <img className="user_sayImg" src={item.img_url} alt=""/>
                        }
                    </div>
                </div>
            </div>
        );

        const myDate = this.state.can_load_time <= 1 ?
            <div>
                {serverDate}
            </div> :
            <InfiniteScroll
                pageStart={0}
                loadMore={this.loadMore}
                hasMore={this.state.isLoadMore}
                threshold={10}
                isReverse={true}
                initialLoad={false}
                loader={<span></span>}
                useWindow={false}
            >
                {serverDate}
            </InfiniteScroll>

        return myDate
    }

    render() {
        const detailInfo = this.createDom();
        return (
            <div className="weui-tab">
                <div ref="tab_panel" className="weui-tab__panel">
                    {detailInfo}
                    <div ref='scrollIntoView'></div>
                </div>
                <div className="send_suggestion weui-tabbar">
                    <div className="sendInput">
                        <input type="text" value={this.state.addContent} onFocus={this.inputFocus}
                               onChange={this.handleChangeContent}/>
                    </div>

                    <a href="javascript:;" style={{fontSize: 13, lineHeight: 2.5,width:62}}
                       className="weui-btn weui-btn_mini weui-btn_yellow" onClick={this.sendSuggestion}>发送</a>
                </div>
            </div>
        )
    }
}
ReactDOM.render(<SuggestionDetail />, document.getElementById('app'));
if (module.hot) {
    module.hot.accept();
}

